# ser-cfg.pm
# Copyright (C) 2006  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 
# This file is part of the CarrierClass.net project.
# For more information: http://carrierclass.net/
#

# This file is part of the CarrierClass.net project.
# For more information: http://carrierclass.net/
#

package CCNv2::Provision::Asterisk::voicemail;
use strict;
use warnings;
use base qw(CCNCore::Provision::Base);
use CCN::Text;
use CCNCore::Scripting;
use CCNCore::Home;

sub run()
{
    my $self = shift;
    return unless defined $self->p->{vm_member};

    $self->PACKAGE ('sipsak');
    $self->CHECKFOR('/usr/bin/sipsak');

    # YYY Replace with an outbound cluster specific to VM (the same as it used to be in 2.0) ?
    my $PROXY = $self->sql_get(q(SELECT default_outbound_px_cluster FROM vm_clusters WHERE pk = ?),$self->p->{vm_member});
    return $self->error ("You must specify an outbound proxy cluster for voicemail cluster ".$self->p->{vm_member})
        if not defined $PROXY;

    # Configure sipsak for notifications

    for my $f (CCNCore::Home::config.'/local/bin/local-sipsak-notify.pl')
    {
        my $r = template(CCNCore::Home::manager.'/lib/templates/sipsak.pl',$f,
            {
                'SERVER' => $self->get_realtime_ip_of($self->p->server_pk),
                'PROXY'  => $self->p->make_cluster_name($PROXY,'px'),
            } );
        $self->log($r) if $r;
        CCN::Scripting::exec_command("chmod +x $f");
    }

    # Collect all the timezones for all the enterprises that could use this cluster.
    $self->PACKAGE ('sipsak');
    
    our @need_tzs = ();

    $self->sql_do_for( <<'SQL', $self->p->{vm_member},
        SELECT DISTINCT timezone FROM pool WHERE enterprise IN (SELECT enterprise FROM voicemail WHERE cp_cluster = ?)
SQL
    sub
    {
        push @need_tzs, shift;
    });

    # Build the definitions for the timezones we support on this cluster.
    our $tz_defs = '';
    for my $tz_name (@need_tzs)
    {
        my $tz_label = lc($tz_name);
        $tz_label =~ s/[^\w]/_/g;
        $tz_defs .= <<"EOT";
${tz_label}_12=$tz_name|'vm-received' Q 'digits/at' IMp
${tz_label}_24=$tz_name|'vm-received' q 'digits/at' HM
EOT
    }

    my $TZ_DEFS = $tz_defs;

    # vm-notify.sh is defined in configure_replication

    my $SERVER = $self->p->server_name;
    my $home_config = CCNCore::Home::config;
    CAT '/etc/asterisk/voicemail.conf', copyright('; voicemail.conf').<<"EOT";
;
; Voicemail Configuration
;
[general]
searchcontexts=yes
;
format=wav49
serveremail=voicemail\@${SERVER}
attach=yes
maxmessage=180
minmessage=0
maxgreet=60
skipms=3000
maxsilence=10
silencethreshold=128
maxlogins=3
externnotify=$home_config/local/bin/vm-notify.sh
;externpass=/usr/bin/myapp
;directoryintro=dir-intro
;charset=ISO-8859-1
;
;adsifdn=0000000F
;adsisec=9BDBF7AC
;adsiver=1
pbxskip=yes
fromstring=Voicemail
pagerfromstring=Voicemail
;
emailsubject=Voicemail from \${VM_CALLERID}
emailbody=Message #\${VM_MSGNUM} from \${VM_CALLERID} left at \${VM_DATE} -- \${VM_DUR}\\n\\n
;
;mailcmd=/usr/sbin/sendmail -t
;
tz=UTC
attach=yes
; saycid=yes
; dialout=fromvm
; sendvoicemail=yes
; callback=fromvm
review=yes
; operator=yes
; envelope=no
; delete=yes
nextaftercmd=yes

[zonemessages]
${TZ_DEFS}
EOT

    IF_CHANGED '/etc/asterisk/voicemail.conf' => CCNv2::Scripting::AST('reload app_voicemail.so');
    IF_CHANGED '/etc/asterisk/voicemail.conf' => CCNv2::Scripting::AST('reload app_hasnewvoicemail.so');
    # TBD What else?

    COMMIT_MODULE(ref($self));
}

sub commit()
{
    my $self = shift;

    # Keep VM_DANGLING_LOCK_WAIT long enough to allow people to sit in voicemail for a little while.
    our $VM_DANGLING_LOCK_WAIT = 30; # minutes
    # How often are messages purged from voicemail (unconditionally)
    our $VM_MESSAGES_PURGE     = 45; # days

    use CCNCore::Scripting;
    CCNCore::Scripting::CRONTAB qq(*/10 * * * * nice -n 1 find /var/spool/asterisk/voicemail -type f -name ".lock*" -mmin  +${VM_DANGLING_LOCK_WAIT} -print0 | xargs -r -0 rm);
    CCNCore::Scripting::CRONTAB qq(*/10 * * * * nice -n 2 find /var/spool/asterisk/voicemail -type f -name "msg*"   -size  0c                        -print0 | xargs -r -0 rm);
    CCNCore::Scripting::CRONTAB qq(*/10 * * * * nice -n 1 find /var/spool/asterisk/voicemail -type f -name ".lock*" -mmin  +${VM_DANGLING_LOCK_WAIT} -print0 | xargs -r -0 rm);
    CCNCore::Scripting::CRONTAB qq(15   5 * * * nice -n 2 find /var/spool/asterisk/voicemail -type f -name "msg*"   -mtime +${VM_MESSAGES_PURGE}     -print0 | xargs -r -0 rm);
    # TBD Purge .txt without .wav
}
1;